<?php

namespace App\Http\Controllers\Customer;

use App\Common\Fun;
use App\Models\Customer\CustomerModel;
use App\Models\Customer\CustomerOauthModel;
use App\Service\Customer\CustomerCodeService;
use App\Service\Customer\CustomerOauthService;
use App\Service\Customer\CustomerProgram;
use App\Service\Customer\CustomerTokenService;
use App\Service\Easemob\EasemobService;
use App\Service\Jpush\JpushService;
use App\Service\Work\BestWorksService;
use DB;
use Storage;
use App\Http\Controllers\Controller;
use App\Service\Customer\CustomerService;
use App\Service\Ses\SesService;
use Illuminate\Http\Request;
use App\Common\Result;
use App\Service\ServiceLog;
use Mail;
class CustomerController extends Controller
{
    /**
     * 注册用户
     * @param Request $request
     */
    public function register(Request $request)
    {
        //检查邮箱密码验证码是否为空
        Result::isEmpty($request->email, "邮箱不能为空",-5);
        Result::isEmpty($request->password, "密码不能为空",-1);
        Result::isEmpty($request->code, "验证码不能为空",-2);

        $SesService = new SesService();
        //检查邮箱注册情况
        $SesService->checkUser($request->email);

        $info = [
            'email'=>$request->email,
            'password'=>$request->password,
            'nickname'=> substr($request->email,0,4)."****".".com",
            'headimgurl'=>"https://xfapi.peddler.cn/headimg/default_header.jpg"
        ];

        $verify_code = CustomerCodeService::getVerifyCode([
            'email' => $request->email,
            'code' => $request->code
        ]);

        if(!$verify_code){
            Result::msg('-3', 'error', '验证码不正确');
        }

        //添加新用户
        $responce = CustomerService::createUser($info);

        //获得官方账号扩展
        $ext = Controller::getSendExt('sj_00000000000002');
        if($responce){
            //推送信息
            JpushService::pushMessage($responce['uid'],'欢迎来到小贩APP,这里有最全最新的资源!',$ext);
            Result::msg('0','success',$responce);
        }else{
            Result::msg('-4', 'error', '创建用户失败');
        }
    }

    /**
     * 用户账号登入
     * @param Request $request
     */
    public function login(Request $request)
    {
        Result::isEmpty($request->email,'邮箱不能为空',-5);
        Result::isEmpty($request->password,'密码不能为空',-1);


        $password = Result::md5_pwd($request->password);
        $responce = CustomerService::checkPwd($request->email, $password);
        //获得官方账号扩展
        $ext = Controller::getSendExt('sj_00000000000002');

        if($responce['result']){
            CustomerService::UserLoginFollow($responce['data']['uid']);
            //jpush推送
            JpushService::pushMessage($responce['data']['uid'],"欢迎来到小贩APP,这里有最全最新的资源!",$ext);
            Result::msg('0','success',$responce['data']);
        }else{
            Result::msg($responce['code'],'error',$responce['message']);
        }
    }

    /**
     * 第三方登入
     * @param Request $request
     */
    public function oauth(Request $request)
    {
        Result::isEmpty($request->openid,'无有效OpenId',-15);
        //Result::isEmpty($request->nickname,'无有效用户信息',-16);

        //获得官方账号扩展
        $ext = Controller::getSendExt('sj_00000000000002');
        if($oauthInfo = CustomerOauthService::findUser(
        //查询用户是否已经注册
            [   'openid'=>$request->openid,
                'source'=>$request->source ])){
            $uid = $oauthInfo->uid;
            $customer_info = CustomerService::findUser(['uid'=>$uid]);
            if(!$customer_info){
                $info = [
                    'uid' => $uid,
                    'headimgurl' => $request->headimgurl,
                    'sex' => $request->sex,
                    'address' => $request->address
                ];
                $responce = CustomerService::createUser($info);

                if($responce)
                {
                    CustomerService::UserLoginFollow($responce['uid']);
                    //环信发送消息 token重置
                    $easeService = new EasemobService();
                    $easeService->registerEaseUser($responce['uid'],$responce['uid'],$responce['nickname']);
                    $easeService->sendText('sj_00000000000002',[$uid],'欢迎来到小贩APP,这里有最全最新的资源!',$ext,'cmd');
                    $token_info = CustomerTokenService::generate($uid);
                    $responce['token'] = $token_info['token'];
                    $responce['expire'] = $token_info['expire'];
                    //jpush推送
                    JpushService::pushMessage($uid,"欢迎来到小贩APP,这里有最全最新的资源!",$ext);
                    Result::msg('0','success',$responce);
                }else{
                    Result::msg('-4', 'error', '创建用户失败');
                }

            }else {
                //更新用户信息
                $info = [
                    'headimgurl' => $request->headimgurl,
                    'sex' => $request->sex
                ];

                $responce = CustomerService::updUser($uid,$info);
                if($responce)
                {
                    CustomerService::UserLoginFollow($uid);
                    //环信发送消息 token重置
                    $easeService = new EasemobService();
                    $easeService->sendText('sj_00000000000002',[$uid],'欢迎来到小贩APP,这里有最全最新的资源!',$ext,'cmd');
                    $token_info = CustomerTokenService::generate($uid);
                    $responce['token'] = $token_info['token'];
                    $responce['expire'] = $token_info['expire'];
                    $responce['nickname'] = $customer_info->nickname;
                    //jpush推送
                    JpushService::pushMessage($uid,"欢迎来到小贩APP,这里有最全最新的资源!",$ext);
                    Result::msg('0','success',$responce);
                }else{
                    Result::msg('-11', 'error', '更新失败');
                }
            }
        }else{
            $data = [
                'openid' => $request->openid,
                'source' => $request->source,
                'nickname' => CustomerService::creatRandNickname(),
                'headimgurl' => $request->headimgurl
            ];
            $responce = CustomerService::createOauth($data);
            if($responce['result']){
                CustomerService::UserLoginFollow($responce['uid']);
                //发送消息 环信注册用户
                $easeService = new EasemobService();
                $easeService->registerEaseUser($responce['uid'],$responce['uid'],$responce['nickname']);
                $easeService->sendText('sj_00000000000002',[$responce['uid']],'欢迎来到小贩APP,这里有最全最新的资源!',$ext,'cmd');
                $token_info = CustomerTokenService::generate($responce['uid']);
                $responce['token'] = $token_info['token'];
                $responce['expire'] = $token_info['expire'];
                //jpush推送
                JpushService::pushMessage($responce['uid'],"欢迎来到小贩APP,这里有最全最新的资源!",$ext);
                Result::msg('0','success',$responce);
            }else{
                Result::msg('-8','error',$responce['message']);
            }
        }
    }

    /**
     * 发送邮箱验证码
     * @param Request $request
     */
    public function sendCode(Request $request)
    {
        //检查邮箱密码是否为空
        Result::isEmpty($request->email, "邮箱不能为空",-5);
		Result::isEmpty($request->code,"状态为空",-26);
        //检查邮箱是否已经注册
        $user_info = CustomerService::findUser([
            'email' => $request->email,
        ]);
        if($user_info && $request->code == 1){
            Result::msg('-20','error','邮箱已经被注册');
        }
		if($request->code != 1 && !$user_info){
			Result::msg('-16','error','没有此账号');
		}
        //发送邮件
        $SesService = new SesService();
        $SesService->sendEmail($request->email);
        $responce = array();
        Result::msg('0','success',$responce);

    }

    /**
     * 修改头像
     */

    public function changeHeadImg(Request $request)
    {
        $uid = $request->uid;
        //上传文件
		/*$article_info = BestWorksService::findArticle([
            'author_uid' => $uid
        ]);*/
        $user_info = CustomerService::findUser([
            'uid' => $uid,
            'is_author' => 1
        ]);
        if($user_info){
            Result::msg('-26','error','作者修改头像需要申请!');
        }
        /*if(!$request->hasFile('avatar')){
            Result::msg('-9','error','上传文件为空!');
        }
        $file = $request->file('avatar');

        if(!$file->isValid()){
            Result::msg('-10','error','文件上传出错!');
        }
        $newFileName = date('Y-m-d') . '-' . uniqid() . '.'.$file->getClientOriginalExtension();
        $bytes = Storage::disk('headimg')->put(
            $newFileName,
            file_get_contents($file->getRealPath())
        );
        if($bytes){
            $path = asset("headimg/$newFileName");
        }*/

        $qiniu_config = config("qiniu.qiniu");
        $imgurl = $request->imgpath;
        //add data
        $data = array(
            'headimgurl' => $qiniu_config['imgPath'].$imgurl,
        );
        if(CustomerService::changeUser($uid,$data)){
            Result::msg('0','success',$data);
        }else{
            Result::msg('-11','error','更新失败');
        }
    }

    /**
     * 修改昵称
     */
    public function changeNickname(Request $request)
    {
        Result::isEmpty($request->uid,'无有效用户信息',-16);
        Result::veryShort($request->nickname);
        $uid = $request->uid;
        $is_author = CustomerService::findUser([
            'uid' => $uid,
            'is_author' => 1
        ]);

        if($is_author){
            Result::msg('-27','error','作者修改昵称需要申请!');
        }
        $data = array(
            'nickname' => $request->nickname
        );
        $user_info = CustomerService::findUser([
            'uid' => $request->uid
        ]);
        if(!$user_info){
            Result::msg('-16','error','无有效用户信息');
        }
        if($user_info->nickname == $request->nickname){
            Result::msg('-19','error','昵称不能与原先一样');
        }
        $responce = CustomerService::changeUser($uid, $data);
        if($responce){
            //环信修改昵称
            $easemob = new EasemobService();
            $easemob->setNickname($uid,$data['nickname']);

            Result::msg('0','success',$data);
        }else{
            Result::msg('-11','error','更新失败');
        }
    }

    /**
     * 重新设置密码
     */
    public function setPassword(Request $request)
    {

        Result::isEmpty($request->email,'邮箱不能为空',-5);
        Result::isEmpty($request->password,'密码不能为空',-1);

        //$uid = $request->uid;
        $email = $request->email;
        $code = $request->code;
        $password = Result::md5_pwd($request->password);


        $data = array(
            'email' => $email
        );
        if(!$Customers = CustomerService::findUser($data)){
            Result::msg('-12', 'error', '账号和邮箱不对');
        }
		
        $verify_code = CustomerCodeService::getVerifyCode([
            'email' => $email,
            'code' => $code
        ]);

        if(!$verify_code){
            Result::msg('-3', 'error', '验证码不正确');
        }

        $info = array(
            'password'=>$password
        );
        $responce = CustomerService::changeUser($Customers->uid,$info);
        if($responce){
            Result::msg('0','success',$data);
        }else{
            Result::msg('-11','error','更新失败');
        }
    }
	
	/**
     * 介绍
     * @param Request $request
     */
    public function setIntroduce(Request $request)
    {
        Result::isEmpty($request->uid,'无有效用户信息',-16);
        Result::isEmpty($request->introduce,'介绍不能为空',-16);
        $user_info = CustomerService::findUser([
            'uid' => $request->uid
        ]);
        if(!$user_info){
            Result::msg('-16','error','无有效用户信息');
        }

        $result = CustomerService::setIntroduce($request->uid,$request->introduce);
        $data = array(
            'introduce'=> $request->introduce
        );
        if($result)
        {
            Result::msg('0','success',$data);
        }else{
            Result::msg('-11','error','更新失败');
        }
    }

    /**
     * 用户头像
     */
    public function getCustomerHeadimg(Request $request)
    {
        $uid = $request->uid;
        $customer_info = CustomerService::findUser(['uid'=>$uid]);
        $data = new Result();
        $data->nickname = $customer_info->nickname;
        $data->headimgurl = $customer_info->headimgurl;
        Result::msg('0','success',$data);
    }

    /**
     *  小程序登入
     */
    public function programLogin(Request $request)
    {
        $code = $request->input('code','');
        if(!$code){
            Result::msg(-1,'error','参数为空');
        }
        try{
            $res = CustomerProgram::sendCode2Session($code);
            $user = CustomerOauthService::findUser([
                'openid' => $res['openid'],
                'source' => 'wx_program'
            ]);

            if(!$user){
                Result::msg(10000,'error','未注册');
            }
            $data = CustomerTokenService::generate($user->uid);
            Result::msg(0,'success',$data);
        }catch (\Exception $e){

            Result::msg(-1,'error',$e->getMessage());
        }
    }

    /**
     *  小程序注册
     */
    public function programRegister(Request $request)
    {
        $code = $request->input('code','');
        if(!$code){
            Result::msg(-1,'error','参数为空');
        }
        $user_info = $request->input('userinfo','');
        $user_info = json_decode($user_info,true);

        \DB::beginTransaction();
        try{
            $res = CustomerProgram::sendCode2Session($code);
            $user = CustomerOauthService::findUser([
                'openid' => $res['openid'],
                'source' => 'wx_program'
            ]);
            if(!$user){
                //没有注册再去注册
                $customer = CustomerService::createUser([
                    'nickname' => $user_info['nickName'],
                    'headimgurl' => $user_info['avatarUrl']
                ]);
                CustomerOauthModel::create([
                    'uid' => $customer['uid'],
                    'openid' => $res['openid'],
                    'source' => 'wx_program',
                    'nickname' => $user_info['nickName'],
                    'sex' => $user_info['gender'],
                    'headimgurl' => $user_info['avatarUrl'],
                    'city' => $user_info['city'],
                    'province' => $user_info['province'],
                    'country' => $user_info['country']
                ]);
            }
            \DB::commit();
            Result::msg(0,'success','');
        }catch (\Exception $e){
            \DB::rollBack();
            Result::msg(-1,'error',$e->getMessage());
        }
    }

    /**
     * @param Request $request
     * 小程序token检验
     */
    public function checkToken(Request $request)
    {
        $uid = $request->input('uid','');
        $token = $request->input('token','');

        if(!$uid || !$token){
            Result::msg(-1,'error','缺少关键参数');
        }
        $user_token = CustomerTokenService::getToken($uid);

        if(!$user_token || $user_token->token != $token || (time()-$user_token->token_expire)>7200){
            Result::msg(-1,'error','token失效,重新授权登入');
        }
        Result::msg(0,'success','');
    }

    /**
     * 获得用户信息
     */
    public function userDetail(Request $request)
    {
        $uid = $request->input('uid','');
        if(!$uid){
            Result::msg(-1,'error','缺少关键参数');
        }
        $data = CustomerService::findUser(['uid'=>$uid]);
        Result::msg(0,'success',$data);
    }

    /**
     *  修改手机号
     */
    public function changeMobile(Request $request)
    {
        $uid = $request->input('uid','');
        $mobile = $request->input('mobile','');
        CustomerService::changeUser($uid,[
            'mobile' => $mobile
        ]);
        Result::msg(0,'success',[]);
    }
}
        